package com.fullertontech.framework.rabbitmq;

import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

public class RabbitConfig {
	@Value("${mq.host}")
	private String host;
	@Value("${mq.port}")
	private Integer port;
	@Value("${mq.username}")
	private String username;
	@Value("${mq.password}")
	private String password;
	@Value("${mq.vhost}")
	private String virtualHost;
	
	@Bean
	public CachingConnectionFactory productCachingConnectionFactory() {
		CachingConnectionFactory connectionFactory=new CachingConnectionFactory();
		connectionFactory.setHost(host);
		connectionFactory.setPort(port);
		connectionFactory.setUsername(username);
		connectionFactory.setPassword(password);
		connectionFactory.setVirtualHost(virtualHost);
		return connectionFactory;
	}
	
	@Bean
    @Scope("prototype") //必须是prototype类型
	public RabbitTemplate productRabbitTemplate(CachingConnectionFactory cachingConnectionFactory,Jackson2JsonMessageConverter jackson2JsonMessageConverter) {
		RabbitTemplate rabbitTemplate=new RabbitTemplate(cachingConnectionFactory);
		rabbitTemplate.setChannelTransacted(false);
		rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter);
		return rabbitTemplate;
	}
	@Bean
	public RabbitAdmin productRabbitAdmin(CachingConnectionFactory cachingConnectionFactory) {
		RabbitAdmin rabbitAdmin=new RabbitAdmin(cachingConnectionFactory);
		return rabbitAdmin;
	}
	@Bean
	public Jackson2JsonMessageConverter productJackson2JsonMessageConverter() {
		Jackson2JsonMessageConverter jackson2JsonMessageConverter=new Jackson2JsonMessageConverter();
		return jackson2JsonMessageConverter;
	}
	@Bean
	public RabbitClient productRabbitClient(RabbitTemplate rabbitTemplate,CachingConnectionFactory connectionFactory) {
		RabbitClient rabbitClient=new RabbitClient();
		rabbitClient.setConnectionFactory(connectionFactory);
		return rabbitClient;
	}
	@Bean
	public MessageListener productMessageListener(RabbitClient rabbitClient) {
		MessageListener messageListener=new MessageListener();
		messageListener.setAcknowledgeMode(AcknowledgeMode.AUTO);
		messageListener.setRabbitClient(rabbitClient);
		return messageListener;
	}
}
